import { assessmentFillApi } from "../../utils/api"

// KPI填写页面逻辑
Component({
  data: {
    // KPI填充详情数据
    kpiFillDetails: [],
    
    // 加载状态
    loading: false,
    
    // 空状态提示
    emptyText: '暂无KPI数据',
    
    // 当前考核ID
    assessmentId: '',
    
    // 表单验证状态
    formValid: false
  },

  methods: {
    // 页面加载时初始化
    onLoad(options: any) {
      console.log('KPI填写页面参数:', options)
      
      if (options && options.id) {
        this.setData({
          assessmentId: options.id
        })
        this.loadKpiFillData()
      } else {
        wx.showToast({
          title: '参数错误',
          icon: 'error',
          duration: 2000
        })
        setTimeout(() => {
          wx.navigateBack()
        }, 2000)
      }
    },

    handlerGobackClick() {
      wx.navigateBack({
        delta: 1
      })
    },

    // 加载KPI填充数据
    async loadKpiFillData() {
      this.setData({ loading: true })
      
      try {
        // 调用API获取KPI详情数据
        const res = await assessmentFillApi.getKpiFillDetails(this.data.assessmentId)
        
        console.log('KPI填充数据响应:', res)
        
        if (res.code === 200 && res.data) {
          // 处理API返回的数据，添加验证状态字段
          const kpiData = Array.isArray(res.data) ? res.data : [res.data]
          const processedData = kpiData.map((item: any) => ({
            id: item.id || '',
            kpiId: item.kpiId || '',
            kpiName: item.kpiName || '',
            fillId: item.fillId || '',
            selfScore: item.selfScore || '',
            selfComment: item.selfComment || '',
            pickerValue: item.selfScore ? parseInt(item.selfScore) - 1 : 0,
            scoreError: ''
          }))
          
          this.setData({
            kpiFillDetails: processedData,
            loading: false
          })
        } else {
          // API调用失败，使用模拟数据
          console.warn('API调用失败，使用模拟数据:', res.msg)
          const mockData = this.getMockKpiFillData()
          
          this.setData({
            kpiFillDetails: mockData,
            loading: false,
            emptyText: res.msg || '暂无KPI数据'
          })
        }
        
        // 检查表单验证状态
        this.checkFormValidity()
        
      } catch (error) {
        console.error('加载KPI数据失败:', error)
      }
    },

    // 分数选择处理
    onScoreChange(e: any) {
      const { value } = e.detail
      const { index } = e.currentTarget.dataset
      
      const kpiFillDetails = this.data.kpiFillDetails
      
      // picker的value是选中的索引，需要+1得到实际分数
      const selectedScore = parseInt(value) + 1
      
      kpiFillDetails[index].selfScore = selectedScore.toString()
      kpiFillDetails[index].pickerValue = parseInt(value)
      kpiFillDetails[index].scoreError = ''
      
      this.setData({ kpiFillDetails })
      
      // 检查表单验证状态
      this.checkFormValidity()
    },

    // 评语输入处理
    onCommentInput(e: any) {
      const { value } = e.detail
      const { index } = e.currentTarget.dataset
      
      const kpiFillDetails = this.data.kpiFillDetails
      kpiFillDetails[index].selfComment = value
      
      this.setData({ kpiFillDetails })
      
      // 检查表单验证状态
      this.checkFormValidity()
    },

    // 检查表单验证状态
    checkFormValidity() {
      const kpiFillDetails = this.data.kpiFillDetails
      let formValid = true
      
      for (const item of kpiFillDetails) {
        // 检查分数是否填写且有效
        if (!item.selfScore || item.selfScore.trim() === '' || item.scoreError) {
          formValid = false
          break
        }
        
        // 检查评语是否填写
        if (!item.selfComment || item.selfComment.trim() === '') {
          formValid = false
          break
        }
      }
      
      this.setData({ formValid })
    },

    // 提交表单
    async onSubmit() {
      if (!this.data.formValid) {
        wx.showToast({
          title: '请完善所有必填项',
          icon: 'none',
          duration: 2000
        })
        return
      }

      // 显示加载中
      wx.showLoading({
        title: '提交中...',
        mask: true
      })

      try {

        // 调用API提交KPI评分
        const res = await assessmentFillApi.submitKpiFill(this.data.kpiFillDetails)
        
        if (res.code !== 200) {
          throw new Error(res.msg || '提交失败')
        }

        wx.showToast({
          title: '提交成功',
          icon: 'success',
          duration: 2000
        })

        // 返回上一页
        setTimeout(() => {
          wx.navigateBack()
        }, 2000)

      } catch (error) {
        console.error('提交失败:', error)
        wx.showToast({
          title: '提交失败，请重试',
          icon: 'error',
          duration: 2000
        })
      } finally {
        wx.hideLoading()
      }
    },

    // 模拟提交KPI填充数据
    async mockSubmitKpiFill(data: any) {
      return new Promise((resolve) => {
        setTimeout(() => {
          console.log('KPI填充数据已提交:', data)
          resolve({ code: 200, msg: '提交成功' })
        }, 1500)
      })
    },

    // 返回上一页
    onBack() {
      wx.navigateBack()
    }
  }
})